package com.xuerhua.yxt.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.xuerhua.yxt.model.*;
import com.xuerhua.yxt.view.ParentRelStudentView;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xuerhua.yxt.common.AppUser;
import com.xuerhua.yxt.common.Const;
import com.xuerhua.yxt.common.MenuConst;
import com.xuerhua.yxt.common.RspResult;
import com.xuerhua.yxt.common.enums.Status;
import com.xuerhua.yxt.common.enums.WeekCommentStatus;
import com.xuerhua.yxt.page.OrderBy;
import com.xuerhua.yxt.page.Page;
import com.xuerhua.yxt.reqVo.BaseQueryVO;
import com.xuerhua.yxt.reqVo.StudentWeekCommentReqVO;
import com.xuerhua.yxt.reqVo.WeekCommentQueryVO;
import com.xuerhua.yxt.service.IOrganizeGroupService;
import com.xuerhua.yxt.service.IParentService;
import com.xuerhua.yxt.service.IStudentService;
import com.xuerhua.yxt.service.IStudentWeekCommentService;
import com.xuerhua.yxt.service.ISysCommentTemplateService;
import com.xuerhua.yxt.service.ISysDictDataService;
import com.xuerhua.yxt.service.ITeacherService;
import com.xuerhua.yxt.utils.DateUtil;
import com.xuerhua.yxt.utils.StringUtil;
import com.xuerhua.yxt.view.StudentWeekCommentView;
import com.xuerhua.yxt.view.TeacherInfoView;
import com.xuerhua.yxt.vo.SysCommentTemplateQueryVO;

@Controller
public class WeekCommentController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(WeekCommentController.class);
	
	@Autowired
	private ITeacherService teacherService;
	@Autowired
	private IStudentService studentService;
	@Autowired
	private IParentService parentService;
	@Autowired
	private IStudentWeekCommentService studentWeekCommentService;
	@Autowired
	private ISysDictDataService sysDictDataService;
	@Autowired
	private ISysCommentTemplateService sysCommentTemplateService;
	@Autowired
	private IOrganizeGroupService organizeGroupService;
	
	private final static String TEACHER_URL = Const.TEACHER_ROLE + MenuConst.WEEK_COMMENT;
	private final static String STUDENT_URL = Const.STUDENT_ROLE + MenuConst.WEEK_COMMENT;
	
	@RequestMapping(TEACHER_URL)
	public String teacherWeekCommentPage(Model model) {
		AppUser appUser = getAppUser();
		int count = organizeGroupService.isLeaderGroup(appUser.getTeacher().getId());
		if(count > 0) {
			return "weekComment/leaderList";
		}
		BaseQueryVO queryVO = new BaseQueryVO();
		queryVO.setFinishYear(getCurrentTerm().getFinishYear());
		queryVO.setId(appUser.getTeacher().getId());
		List<TeacherInfoView> teacherInfoView = teacherService.selectClassForTeacher(queryVO);
		if(StringUtil.isNullOrEmpty(teacherInfoView)) {
			model.addAttribute("flag", 0);
		}
		return "weekComment/teacherPage";
	}
	
	@RequestMapping(STUDENT_URL)
	public String parentWeekCommentPage() {
		return "weekComment/studentPage";
	}
	
	@RequestMapping(TEACHER_URL + "/studentPage/{studentId}")
	public String studentCommentPage(Model model, @PathVariable Integer studentId) {
		model.addAttribute("studentId", studentId);
		return "weekComment/studentPage";
	}
	
	@RequestMapping(TEACHER_URL + "/lookList")
	public String studentCommentLookList(Model model) {
		String weekNo = request.getParameter("wno");
		String grade = request.getParameter("grade");
		String clazz = request.getParameter("clazz");
		model.addAttribute("weekNo", weekNo);
		model.addAttribute("grade", grade);
		model.addAttribute("clazz", clazz);
		return "weekComment/lookList";
	}
	
	@RequestMapping(TEACHER_URL + "/lookList/data")
	@ResponseBody Object studentCommentLookListData(WeekCommentQueryVO vo) {
		AppUser appUser = getAppUser();
		vo.setSchoolId(appUser.getTeacher().getSchoolId());
		vo.setTermId(getCurrentTerm().getId());
		return studentWeekCommentService.selectViewList(vo);
	}

	//TODO /page/weekComment/detail.jsp中的43行对应的(TEACHER_URL+"/write")方法没有
	//老师来这个方法
	@RequestMapping(TEACHER_URL + "/write")
	public String teacherWeekCommentWrite(Model model) {
		AppUser appUser = getAppUser();
		StudentWeekComment studentWeekComment = new StudentWeekComment();
		String studentId = request.getParameter("sid");
		String weekNo = request.getParameter("wno");
		String commentId = request.getParameter("cid");
		studentWeekComment.setSchoolId(appUser.getTeacher().getSchoolId());
		if(StringUtils.isBlank(studentId) || StringUtils.isBlank(weekNo)) {
			return null;
		} else {
			studentWeekComment.setStudentId(Integer.valueOf(studentId));
			studentWeekComment.setWeekNo(Integer.valueOf(weekNo));
		}
		if(StringUtils.isNotBlank(commentId)) {
			studentWeekComment.setId(Integer.valueOf(commentId));
			StudentWeekCommentView comment = studentWeekCommentService.selectViewById(studentWeekComment);
			if(comment.getTeacherId().intValue() != appUser.getTeacher().getId().intValue()) {
				return null;
			}
			model.addAttribute("comment", comment);
		}
		StudentInfo student = studentService.selectById(Integer.valueOf(studentId));
		model.addAttribute("student", student);
		model.addAttribute("weekNo", weekNo);
		return "weekComment/teacherComment";
	}
	
	@RequestMapping(TEACHER_URL + "/detail")
	public String teacherWeekCommentDetail(
			Model model, StudentWeekComment studentWeekComment) {
		AppUser appUser = getAppUser();
		studentWeekComment.setSchoolId(appUser.getTeacher().getSchoolId());
		StudentWeekCommentView detail = studentWeekCommentService.selectViewById(studentWeekComment);
		model.addAttribute("detail", detail);
		if(WeekCommentStatus.TEACHER.getCode() == detail.getStatus() &&
		   detail.getTeacherId().intValue() == appUser.getTeacher().getId().intValue()) {
		   model.addAttribute("isEdit", true);
		}
		return "weekComment/detail";
	}

	//家长来这里
	@RequestMapping(STUDENT_URL + "/detail")
	public String studentWeekCommentDetail(
			Model model, StudentWeekComment studentWeekComment) {
		String edit = request.getParameter("edit");
		studentWeekComment.setSchoolId(getAppUser().getParent().getSchoolId());
		StudentWeekCommentView detail = studentWeekCommentService.selectViewById(studentWeekComment);
		model.addAttribute("detail", detail);
		//老师已评或者edit不是空就进去
		if(detail.getStatus() == WeekCommentStatus.TEACHER.getCode() || StringUtils.isNotBlank(edit)) {
			return "weekComment/studentComment";
		}
		if(DateUtil.compare(DateUtil.addDay(detail.getParentCommentTime(), 1), new Date()) >= 0) {
			model.addAttribute("isEdit", true);
		}
		return "weekComment/detail";
	}
	
	@RequestMapping(TEACHER_URL + "/studentList")
	@ResponseBody Object studentWeekCommentList(WeekCommentQueryVO vo) {
		try {
			AppUser appUser = getAppUser();
			BaseQueryVO queryVO = new BaseQueryVO();
			queryVO.setFinishYear(getCurrentTerm().getFinishYear());
			queryVO.setId(appUser.getTeacher().getId());
			if(vo.getClazz() == null) {
				List<TeacherInfoView> teacherInfoView = teacherService.selectClassForTeacher(queryVO);
				if (teacherInfoView != null && teacherInfoView.size() > 0) {
					vo.setGrade(teacherInfoView.get(0).getGrade());
					vo.setClazz(teacherInfoView.get(0).getClazz());
				}else {
					for(TeacherInfoView record : teacherInfoView) {
						if(record.getGrade().intValue() == appUser.getTeacher().getGrade().intValue()) {
							vo.setGrade(record.getGrade());
							vo.setClazz(record.getClazz());
						}
					}
				}
			}
			vo.setSchoolId(appUser.getTeacher().getSchoolId());
			vo.setTermId(getCurrentTerm().getId());
			return studentWeekCommentService.selectWeekCommentListForStudent(vo);
		} catch (Exception e) {
			logger.error("--studentWeekCommentList error={}", e);
		}
		return null;
	}
	
	@RequestMapping(Const.TEACHER_ROLE + MenuConst.WEEK_COMMENT + "/page")
	@ResponseBody Object weekCommentPageForTeacher(WeekCommentQueryVO vo) {
		try {
			AppUser appUser = getAppUser();
			vo.setSchoolId(appUser.getTeacher().getSchoolId());
			vo.setTermId(getCurrentTerm().getId());
			Page<StudentWeekComment> page = new Page<>();
			Grid grid = new Grid();
			List<OrderBy> sorts = new ArrayList<>();
			sorts.add(new OrderBy("WEEK_NO"));
			page.setSorts(sorts);
			page.setParams(vo);
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			List<StudentWeekComment> list = studentWeekCommentService.selectWeekCommentListByPage(page);
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return grid;
		} catch (Exception e) {
			logger.error("--studentWeekCommentPage error={}", e);
		}
		return null;
	}
	
	@RequestMapping(Const.STUDENT_ROLE + MenuConst.WEEK_COMMENT + "/page")
	@ResponseBody Object weekCommentPageForParent(WeekCommentQueryVO vo) {
		try {
			AppUser appUser = getAppUser();
			vo.setSchoolId(appUser.getParent().getSchoolId());
			vo.setTermId(getCurrentTerm().getId());
			vo.setParentId(appUser.getParent().getId());
			Page<StudentWeekComment> page = new Page<>();
			Grid grid = new Grid();
			List<OrderBy> sorts = new ArrayList<>();
			sorts.add(new OrderBy("WEEK_NO"));
			page.setSorts(sorts);
			page.setParams(vo);
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			List<StudentWeekComment> list = studentWeekCommentService.selectWeekCommentListByPageForParent(page);
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return grid;
		} catch (Exception e) {
			logger.error("--studentWeekCommentPage error={}", e);
		}
		return null;
	}
	
	@RequestMapping(TEACHER_URL + "/studentId")
	@ResponseBody Object weekCommentByStudentId(WeekCommentQueryVO vo) {
		try {
			AppUser appUser = getAppUser();
			vo.setSchoolId(appUser.getTeacher().getSchoolId());
			vo.setTermId(getCurrentTerm().getId());
			return studentWeekCommentService.selectWeekCommentByStudentId(vo);
		} catch (Exception e) {
			logger.error("--weekCommentByStudentId error={}", e);
		}
		return null;
	}
	
	@RequestMapping(TEACHER_URL + "/addAndUpdate")
	@ResponseBody Object teacherWeekCommentSubmit(StudentWeekCommentReqVO reqVO) {
		try {
			AppUser appUser = getAppUser();
			if(reqVO.getId() != null) {
				StudentWeekComment comment = studentWeekCommentService.selectByPrimaryKey(reqVO.getId());
				if(comment == null) {
					return new RspResult(Status.PARAM_FAIL);
				}
				if(WeekCommentStatus.FULL.getCode() == comment.getStatus()) {
					return new RspResult(Status.PARENT_HAD_COMMENT);
				}
				if(appUser.getTeacher().getId().intValue() != comment.getTeacherId().intValue()) {
					return new RspResult(Status.USER_DIFF_COMMENT);
				}
				reqVO.setTeacherUpdateTime(new Date());
				if(reqVO.getAttachIds() != null) {
					reqVO.setIsAttach(1);
				}else{
					reqVO.setIsAttach(0);
				}
				reqVO.setSchoolId(appUser.getTeacher().getSchoolId());
				studentWeekCommentService.updateByPrimaryKeySelective(reqVO);
				return new RspResult(Status.SUCCESS);
			}
			WeekCommentQueryVO vo = new WeekCommentQueryVO();
			vo.setSchoolId(appUser.getTeacher().getSchoolId());
			vo.setTermId(getCurrentTerm().getId());
			vo.setStudentId(reqVO.getStudentId());
			vo.setWeekNo(reqVO.getWeekNo());
			Integer status = studentWeekCommentService.selectStatus(vo);
			if(status != null) {
				return new RspResult(Status.HAD_COMMENT);
			}
			reqVO.setSchoolId(appUser.getTeacher().getSchoolId());
			reqVO.setTermId(getCurrentTerm().getId());
			StudentInfo student = studentService.selectById(reqVO.getStudentId());
			List<ParentRelStudentView> parent = parentService.selectParentListByStudentId(reqVO.getStudentId());
			reqVO.setStudentId(student.getId());
			reqVO.setStudentName(student.getName());
			reqVO.setGrade(student.getGrade());
			reqVO.setClazz(student.getClazz());
			//author hhk
			//父母id和父母名字，取其中一项就够了吧？？
			reqVO.setParentId(parent.get(0).getId());
			reqVO.setParentName(parent.get(0).getName());
			reqVO.setTeacherId(appUser.getTeacher().getId());
			reqVO.setTeacherName(appUser.getTeacher().getName());
			reqVO.setTeacherCommentTime(new Date());
			reqVO.setStatus(WeekCommentStatus.TEACHER.getCode());
			studentWeekCommentService.insert(reqVO);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("--teacherWeekCommentSubmit error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping(STUDENT_URL + "/submit")
	@ResponseBody Object studentWeekCommentSubmit(StudentWeekCommentReqVO reqVO) {
		try {
			//comment已经有schoolId了，这里不用set
			StudentWeekComment comment = studentWeekCommentService.selectByPrimaryKey(reqVO.getId());
			if(comment.getStatus() == WeekCommentStatus.FULL.getCode() && 
					DateUtil.compare(DateUtil.addDay(comment.getParentCommentTime(), 1), new Date()) == -1) {
				return new RspResult(Status.HAD_COMMENT);
			}
			if(comment.getStatus() == WeekCommentStatus.TEACHER.getCode()) {
				AppUser appUser = getAppUser();
				if(appUser != null && appUser.getParent() != null) {
					comment.setParentId(appUser.getParent().getId());
					comment.setParentName(appUser.getParent().getName());
				}else {
					ParentInfo parentInfo = parentService.selectParentById(reqVO.getParentId());
					comment.setParentId(parentInfo.getId());
					comment.setParentName(parentInfo.getName());
				}
				comment.setStatus(WeekCommentStatus.FULL.getCode());
				comment.setParentCommentTime(new Date());
			}else {
				comment.setParentUpdateTime(new Date());
			}
			comment.setParentCommentContent(reqVO.getParentCommentContent());
			comment.setParentCommentType(reqVO.getParentCommentType());
			comment.setStudentCommentContent(reqVO.getStudentCommentContent());
			if(reqVO.getAttachIds() != null) {
				reqVO.setIsAttach(1);
			}else{
				reqVO.setIsAttach(0);
			}
			studentWeekCommentService.updateByPrimaryKeySelective(comment);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("--studentWeekCommentSubmit error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping(TEACHER_URL + "dictData/dictCode")
	@ResponseBody Object dictDataDictCode(SysDictType sysDictType) {
		return sysDictDataService.selectListByDictCode(sysDictType);
	}
	
	@RequestMapping(TEACHER_URL + "/commentTemplate/page")
	@ResponseBody Object commentTemplatePage(SysCommentTemplateQueryVO vo) {
		try {
			Page<SysCommentTemplate> page = new Page<SysCommentTemplate>();
			List<OrderBy> sorts = new ArrayList<>();
			sorts.add(new OrderBy("CREATE_TIME"));
			vo.setSchoolId(getAppUser().getTeacher().getSchoolId());
			page.setSorts(sorts);
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			page.setParams(vo);
			List<SysCommentTemplate> list = sysCommentTemplateService.selectListByPage(page);
			page.setResults(list);
			return page;
		} catch (Exception e) {
			logger.error("--commentTemplatePage error={}", e);
		}
		return null;
	}
	
	@RequestMapping(TEACHER_URL + "/currWeek")
	@ResponseBody Object currWeek(WeekCommentQueryVO vo) {
		AppUser appUser = getAppUser();
		vo.setSchoolId(appUser.getTeacher().getSchoolId());
		vo.setTermId(getCurrentTerm().getId());
		return studentWeekCommentService.selectWeekNo(vo);
	}
}
